import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:mall/core/models/ad.dart';
import 'package:mall/core/services/api.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class AdStartView extends StatefulWidget {
  final int maxSeconds;
  final Function dismiss;

  const AdStartView({
    Key key,
    @required this.maxSeconds,
    @required this.dismiss,
  }) : super(key: key);

  @override
  _AdStartViewState createState() => _AdStartViewState();
}

class _AdStartViewState extends State<AdStartView> {
  Ad _ad;
  int _start;
  Timer _timer;

  @override
  void initState() {
    super.initState();
    _fetchAdStart();
    _start = widget.maxSeconds;
    _timer = Timer.periodic(
      Duration(seconds: 1),
      (timer) {
        if (_start <= 1) {
          timer.cancel();
          widget.dismiss();
        } else {
          setState(() {
            _start--;
          });
        }
      },
    );
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        _ad == null
            ? Container()
            : Container(
                width: double.infinity,
                height: double.infinity,
                child: CachedNetworkImage(imageUrl: _ad.imageUrl),
              ),
        Align(
          alignment: Alignment.topRight,
          child: GestureDetector(
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 2.w, horizontal: 8.w),
              decoration: BoxDecoration(
                color: Colors.black45,
                borderRadius: BorderRadius.circular(16.w),
              ),
              margin: EdgeInsets.only(top: 24.w, right: 12.w),
              child: Text('$_start | 跳过', style: TextStyle(color: Colors.white)),
            ),
            onTap: widget.dismiss,
          ),
        )
      ],
    );
  }

  /// 获取平台广告
  void _fetchAdStart() async {
    final api = context.read<Api>();
    try {
      final result = await api.adStart();
      if (!mounted) {
        return;
      }
      if (result.isEmpty) {
        return;
      }
      setState(() {
        _ad = result.first;
      });
    } on DioError catch (e) {
      debugPrint("${e.message}");
    }
  }
}
